/********************************************
 * 功能说明: Organization实体与DTO之间接口数据转换实现
 * 模块名称:
 * 系统名称:
 * 软件版权: Frank
 * 系统版本: 1.0.0.1
 * 开发人员:
 * 开发时间: 2019-12-18 18:41:08
 * 审核人员:
 * 相关文档:
 * 修改记录: 修改日期 修改人员 修改说明
 *********************************************/
package com.spring.arch.uaa.web.converter;

import com.spring.arch.common.converter.AbstractConverter;
import com.spring.arch.uaa.model.Organization;
import com.spring.arch.uaa.web.dto.WebOrganizationTreeDTO;
import lombok.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Organization实体与DTO之间接口数据转换实现
 *
 * @author
 * @version 1.0.0.1
 * @since 2019-12-18 18:41:08
 */
@Component
public class WebOrganizationTreeConverter extends AbstractConverter<Organization, WebOrganizationTreeDTO> {

    @Override
    public Organization toModel(@NonNull final WebOrganizationTreeDTO dto) {
        return null;
    }

    @Override
    public WebOrganizationTreeDTO toDTO(Organization organization) {

        WebOrganizationTreeDTO dto = new WebOrganizationTreeDTO();

        dto.setId(organization.getId());
        dto.setName(organization.getName());

        return dto;
    }

    public WebOrganizationTreeDTO toDTO(@NonNull final Set<Organization> set) {

        Organization organization = set.parallelStream().filter(s -> s.getParent() == null).findFirst().get();

        WebOrganizationTreeDTO dto = this.toDTO(organization);
        dto.setChildren(this.toTree(dto, set));

        return dto;
    }

    private List<WebOrganizationTreeDTO> toTree(WebOrganizationTreeDTO dto, Set<Organization> set) {

        List<WebOrganizationTreeDTO> dtoList = new ArrayList<>();

        set.removeIf(s -> s.getId() == dto.getId());
        Set<Organization> childrenSet =
                set.parallelStream().filter(s -> s.getParent().getId() == dto.getId()).collect(Collectors.toSet());

        if(CollectionUtils.isEmpty(childrenSet)) {
            return null;
        }

        childrenSet.forEach(s -> dto.setChildren(this.toTree(this.toDTO(s), set)));

        return dtoList;
    }
}
